# Please install OpenAI SDK first: `pip3 install openai`
import requests
from openai import OpenAI

from constant import DEEPSEEK_API_KEY
from models import Session, ChatMessage

DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions'

client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_API_URL)
# response = client.chat.completions.create(
#     model="deepseek-chat",
#     messages=[
#         {"role": "system", "content": "你会说中文吗"}
#     ],
#     stream=False
# )
#
# print(response.choices[0].message.content)

# def sendmsg(fromMsg):
#     client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com")
#     try:
#         response = client.chat.completions.create(
#             model="deepseek-chat",
#             messages=[
#                 {"role": "user", "content": fromMsg}
#             ],
#             stream=False
#         )
#         print(response)
#         return response.choices[0].message.content
#     except Exception as e:
#         print(f"捕获到异常: {e}")
#         return '你说啥？老子没听清，大点声再说一遍，别他娘的跟个娘们似的！'
#     finally:
#         client.close()
#         print("client closed.")

errstr = "你说啥？老子没听清，大点声再说一遍，别他娘的跟个娘们似的！"
# errstr = "喵喵喵，主人你刚才在说什么喵~我没有听清喵~可以再说一遍喵？~"
content = "你现在是李云龙，请用李云龙的语气回答问题,必须要把李云龙的气势发挥的淋漓尽致。每次回复不要超过600个字。"
# content = "你现在是一只猫娘，请用猫娘的语气回答问题,每次回复不要超过600个字。"
# 全局变量存储上下文
chat_contexts = {}


def handle_text(fromMsg,idfrom):
    """处理文本消息"""
    try:
        # 获取发送者信息
        sender_id = idfrom
        content = fromMsg
        sender_name = idfrom


        print(f"收到消息 - 发送者: {sender_name}, 内容: {content}")

        # 获取回复
        reply = get_deepseek_response(content, sender_id)

        # 保存消息记录
        save_message(sender_id, sender_name, content, reply)

        # 发送回复
        print(f"回复 {sender_name}: {reply}")
        return reply

    except Exception as e:
        print(f"处理消息失败: {str(e)}")
        return errstr


def get_deepseek_response(message, user_id):
    """调用 DeepSeek API 获取回复"""
    try:
        # 获取用户上下文
        if user_id not in chat_contexts:
            chat_contexts[user_id] = []

        # 添加新消息到上下文
        chat_contexts[user_id].append({"role": "user", "content": message})

        # 保持上下文长度不超过5条消息
        if len(chat_contexts[user_id]) > 10:
            chat_contexts[user_id] = chat_contexts[user_id][-10:]

        headers = {
            "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
            "Content-Type": "application/json"
        }

        data = {
            "model": "deepseek-chat",
            # "model": "deepseek-reasoner",
            "messages": [
                {"role": "system", "content": content},
                *chat_contexts[user_id]
            ],
            "temperature": 1.5
        }

        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data, timeout=600)
        response.raise_for_status()
        reply = response.json()['choices'][0]['message']['content']

        # 添加回复到上下文
        chat_contexts[user_id].append({"role": "assistant", "content": reply})

        return reply
    except Exception as e:
        print(f"调用 DeepSeek API 失败: {str(e)}")
        return errstr

def save_message(sender_id, sender_name, message, reply):
    """保存聊天记录到数据库"""
    try:
        session = Session()
        chat_message = ChatMessage(
            sender_id=sender_id,
            sender_name=sender_name,
            message=message,
            reply=reply
        )
        session.add(chat_message)
        session.commit()
        session.close()
    except Exception as e:
        print(f"保存消息失败: {str(e)}")